package com.wf.classRoomTest.customer;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ProducerConsumerDemo {

    private static final int MAX_CAPACITY = 10; // 队列最大容量
    private final BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(MAX_CAPACITY);

    public static void main(String[] args) {
        ProducerConsumerDemo demo = new ProducerConsumerDemo();
        Thread producerThread = new Thread(demo.new Producer());
        Thread consumerThread = new Thread(demo.new Consumer());

        producerThread.start();
        consumerThread.start();
    }

    /**
     * 生产者线程任务，不断地向队列中添加元素。
     */
    class Producer implements Runnable {
        @Override
        public void run() {
            try {
                for (int i = 1; ; i++) { // 使用无限循环表示持续生产
                    System.out.println("正在生产: " + i);
                    queue.put(i); // put方法会阻塞，直到有空间可用
                    Thread.sleep(1000); // 模拟生产过程
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("生产者线程被中断");
            }
        }
    }

    /**
     * 消费者线程任务，不断地从队列中取出并处理元素。
     */
    class Consumer implements Runnable {
        @Override
        public void run() {
            try {
                while (true) { // 使用无限循环表示持续消费
                    Integer value = queue.take(); // take方法会阻塞，直到有元素可取
                    System.out.println("正在消费: " + value);
                    Thread.sleep(1500); // 模拟消费过程，时间比生产长，以观察队列填充情况
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("消费者线程被中断");
            }
        }
    }
}
